# -*- coding: utf-8 -*-
"""
2024-02-12 utils  for windows 
"""

## from winformutils import *
## import winformutils
## from top.wardyan.core.utils import winformutils
## from top.wardyan.core.utils.winformutils import WinCfg

from top.wardyan.core.vo.vos import *
from top.wardyan.core.wdb.core.db import *
from top.wardyan.core.sqlite import sqliteconfigs


TABLECFGSCACHE = {}
BILLSTATUS = {
    "0" : "作废",
    "1" : "草稿",
    "2" : "编辑",
    "3" : "提交",
    "4" : "复核",
    "5" : "审核",
    "6" : "锁定",
    # "7" : "锁定",
    # "8" : "锁定",
    # "9" : "锁定"
}

def saveTableCfg(widgetname : str, tablename : str, cfg : TableCfg) -> None :
    ## wincfg : WinCfg = winformutils.__get_cfg_file__(widgetname)
    logger.debug("保存表格配置,widgetname=" + widgetname + ",tablename=" + tablename)
    wincfg : WinCfg = sqliteconfigs.readConfig(widgetname)

    table : TableCfg = sqliteconfigs.getTableCfg(widgetname, tablename)

    if table is None :
        table = TableCfg()
        table.name = tablename
        ## 暂时只支持一个表格
        wincfg.tables = []
        wincfg.tables.append(table)
    if isinstance(cfg.fields, list) :
        table.fields = ",".join(cfg.fields)

    else :
        table.fields=cfg.fields

    table.height = cfg.height
    table.rowcolor = cfg.rowcolor
    table.name = cfg.name
    table.cols = cfg.cols

    wincfg.tables = []
    wincfg.tables.append(table)
    sqliteconfigs.saveConfigs(wincfg)

    ## 清理缓存
    cachename = widgetname + "_" + tablename
    if cachename in TABLECFGSCACHE :
        TABLECFGSCACHE[cachename] = None





def clearTableCfg(widgetname : str, tablename : str) -> None :
    sqliteconfigs.clearTableCfg(widgetname, tablename)
    ## 清理缓存
    cachename = widgetname + "_" + tablename
    if cachename in TABLECFGSCACHE :
        TABLECFGSCACHE[cachename] = None



def getSQLReplace(sql : str) -> dict :
    rs = {}
    ## TODO
    ## list[dict]
    oks : list[dict] = query(sql, ())
    if oks is not None and len(oks) > 0 :
        for ok in oks :
            key = str(ok["sID"])
            value = ok["xName"]
            rs[key] = value
    return rs

def readTableCfg(widgetname : str, tablename : str) -> TableCfg :
    global TABLECFGSCACHE
    if tablename is None :
        tablename = ""
    rs : TableCfg = None

    ## print(widgetname, tablename)

    cachename = widgetname + "_" + tablename
    if cachename in TABLECFGSCACHE :
        rs = TABLECFGSCACHE[cachename]
    if rs is not None :
        return rs

    ## else

    if True :
        rs : TableCfg = sqliteconfigs.getTableCfg(widgetname, tablename)
        
        cols : list[TableColCfg] = []
        for cc in rs.cols :
            if cc.field == 'sStatus' and cc.replace == "" and cc.sql == "" :
                cc._replaces = BILLSTATUS
            elif cc.dicID is not None and cc.dicID > 0 :
                cc._replaces = sqliteconfigs.readDicts(cc.dicID)
            elif cc.replace is not None and len(cc.replace) > 0 :
                ## cc.replaces = replace.split(",")
                cs = cc.replace.split(",")
                rps = {}
                for i in range(len(cs)) :
                    rps[str(i)] = cs[i]
                cc._replaces = rps
            elif cc.sql is not None and len(cc.sql) > 0 :
                ## 动态SQL
                cc._replaces = getSQLReplace(cc.sql)    
            cols.append(cc)
            
        cols.sort(key=lambda x:x.idx)
        rs.cols = cols
    return rs


def getTableColCfg(widget : str, tablename : str, field : str) -> TableColCfg :
    tablecfg : TableCfg = readTableCfg(widget, tablename)
    rs : TableColCfg = None
    if tablecfg is not None:
        rs = tablecfg.getColCfg(field)
    return rs

def saveTableColCfg(cfg : TableColCfg) :
    ##readTableCfg()
    sqliteconfigs.saveTableColCfg(cfg)


if __name__ == "__main__" :
    ok = readTableCfg("__main__", "maintable")
    ## print(ok)